<template>
  <div class="header">
    <div class="header-content">
      <div class="header-left">
        <div class="logo" @click="onLogo" style="cursor: pointer">
          <img :src="formData.logo" class="logo-img" />
          <span class="logo-text">{{formData.clinicName}}</span>
        </div>
      </div>

      <div class="header-center">
        <!-- <div class="nav-menu">
          <div
            v-for="item in menuItems"
            :key="item.key"
            class="nav-item"
            :class="{ active: activeMenu === item.key }"
            @click="handleMenuClick(item)"
          > 
            <span class="nav-text">{{ item.label }}</span>
            <div v-show="activeMenu == item.key" class="active_line"></div>
          </div>
        </div> -->
        <div class="nav-menu">
          <div
            v-for="item in menuListData"
            :key="item.menuId" 
            class="nav-item"
            :class="{ active: activeMenu === item.menuId }"
            @click="handleMenuClick(item)"
          >
            <span class="nav-text">{{ item.menuName }}</span>
            <div v-show="activeMenu == item.menuId" class="active_line"></div>
          </div>
        </div>
      </div>

      <div class="header-right">
        <img
          src="/assets/dashboard/icon_quanping_nor.svg"
          style="cursor: pointer;"
          title="全屏/退出全屏"
          @click="toggleFullscreen"
        />
        <img src="/assets/dashboard/icon_xiaoxi_nor.svg" v-if="noticeStore.unreadCount == 0" style="cursor: pointer;" @click="handleMessageClick" />
        <el-badge :value="noticeStore.unreadCount" class="item" v-else>
          <img src="/assets/dashboard/icon_xiaoxi_nor.svg" style="cursor: pointer;margin-top:4px" @click="handleMessageClick" />
        </el-badge>
        <!-- 主题切换 -->
        <!-- <div class="theme-wrapper">
          <client-only>
            <ThemeSwitcher />
          </client-only>
        </div> -->
        <el-dropdown @command="handleUserCommand" placement="bottom-end">
          <div class="user-info">
            
            <!-- <el-avatar :size="32" :src="userInfo.avatar" class="user-avatar">
              {{ userInfo.name.charAt(0) }}
            </el-avatar> -->
            <img style="width: 30px; height: 30px;border-radius: 50%;" :src="empInfos?.avatarUrl" />
            <!-- icon_circle_nor.svg -->
            <span class="user-name">{{ empInfos?.empName }}</span>
            <el-icon size="14"	><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <span>个人信息</span>
              </el-dropdown-item>
              <!-- <el-dropdown-item command="settings">
                <span>系统设置</span>
              </el-dropdown-item> -->
              <el-dropdown-item divided command="logout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getUnreadNum} from "@/api/notice";
import {getEmpInfo} from "@/api/dashboard/index"
import type {EmpInfoData} from "@/types/dashboard/index";
import {getMenuList} from "@/api/account"
import {CaretBottom} from "@element-plus/icons-vue";
import { getClinicInfo, updateClinicInfo } from '@/api/clinic/index';
import type { clinicInfo } from '@/types/clinicInfo';

const formData = ref<clinicInfo>({
  clinicId: 0,
  clinicName: '',
  logo: '',
  license: '',
  licenseUrl: '',
  province: '',
  city: '',
  county: '',
  url: [],
  address: '',
  areaCode: [],
});
const empInfos = ref<EmpInfoData>()
const EmpInfoApi = async ()=>{ 
    let res = await getEmpInfo()
    if (res.code !== '200') {
      //ElMessage.error(res.msg);
      return;
    }
    empInfos.value = res.data
}
EmpInfoApi()
import stores from '@/store';
const noticeStore = stores.useNoticeStore();
const getUnreadNumApi = async() => {
  await noticeStore.fetchUnreadNum();
}

getUnreadNumApi()

// 菜单项数据
const menuItems = [
  {
    key: 'dashboard',
    label: '工作台',
    path: '/dashboard',
  },
  {
    key: 'registered',
    label: '挂号',
    path: '/registered',
  },
    {
    key: 'toll',
    label: '收费',
    path: '/toll',
  },
  {
    key: 'examination',
    label: '检查',
    path: '/examination',
  },
  {
    key: 'examinationTest',
    label: '检验',
    path: '/examinationTest',
  },
  {
    key: 'manage',
    label: '管理',
    path: '/manage/managePages/clinic',
  },
  {
    key: 'outpatient',
    label: '门诊',
    path: '/outpatient',
  },
  {
    key: 'execute',
    label: '执行',
    path: '/execute',
  },
  {
    key: 'pharmacy',
    label: '药房',
    path: '/pharmacy',
  },
  {
    key: 'InventoryManage',
    label: '库存',
    path: '/InventoryManage',
  },
  {
    key: 'patient',
    label: '患者',
    path: '/patient',
  },
];

const onLogo = () => { 
  navigateTo('/dashboard');
};
// 当前激活的菜单
const activeMenu = ref('');

// 用户信息
const userInfo = ref({
  name: '张医生',
  avatar: '',
  role: '主治医师',
});
//获取菜单
const menuListData = ref<any[]>([])
const useBaseDataStores = stores.useBaseDataStore();
const route = useRoute();
 
const getMenuListApi = async () => {
  let melist = await stores.useBaseDataStore().fetchMenuList()
  menuListData.value = melist  
  if(melist.length > 0 && route.query.menuId == null){
    handleMenuClick(melist[0])
  }
}

// 处理菜单点击
const handleMenuClick = (item: any) => {
  //console.log(item.menuId,'----------');
  
  activeMenu.value = item.menuId;
  // 使用 Nuxt 的 navigateTo 进行路由跳转
  if(item.children.length > 0){
    navigateTo(item.path+'?menuId='+item.menuId+'&submenuId='+item.children[0].menuId);
  }else{
    //console.log(item.menuId,'-----------');
    navigateTo(item.path+'?menuId='+item.menuId);
  }
};

//消息跳转

const handleMessageClick = () => { 
  navigateTo('/message');
};

// 监听路由变化，更新激活菜单
watch(
  () => route.path,
  async (newPath) => {

    let melist = await stores.useBaseDataStore().fetchMenuList()
    menuListData.value = melist  
    const currentMenu = menuListData.value.find((item:any) => item.menuId == route.query.menuId);
    if (currentMenu) {
      activeMenu.value = currentMenu.menuId;
    }else{
      activeMenu.value = '';
    }
    getUnreadNumApi()
  },
  { immediate: true }
);

// 处理用户下拉菜单
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      //console.log('打开个人信息');
      navigateTo('/individual/individualPage');
      break;
    case 'settings':
      //console.log('打开系统设置');
      break;
    case 'logout':
      handleLogout();
      break;
  }
};

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      
      // 这里添加退出登录逻辑
      //console.log('退出登录');
      ElMessage.success('已退出登录');
      removeToken();
      navigateTo('/login');
      useBaseDataStores.resetState()
    })
    .catch(() => {
      // 用户取消
    });
};

// 初始化
onMounted(() => {
  // 可以从路由或其他地方获取当前激活的菜单
  // activeMenu.value = getCurrentActiveMenu()
  getMenuListApi()
});
const onLoin = () => { 

}

// 全屏切换
const isFullscreen = () => {
  return (
    document.fullscreenElement ||
    // @ts-ignore
    document.webkitFullscreenElement ||
    // @ts-ignore
    document.mozFullScreenElement ||
    // @ts-ignore
    document.msFullscreenElement
  );
};

const requestFullscreen = (el: any) => {
  if (el.requestFullscreen) return el.requestFullscreen();
  if (el.webkitRequestFullscreen) return el.webkitRequestFullscreen();
  if (el.mozRequestFullScreen) return el.mozRequestFullScreen();
  if (el.msRequestFullscreen) return el.msRequestFullscreen();
};

const exitFullscreen = () => {
  if (document.exitFullscreen) return document.exitFullscreen();
  // @ts-ignore
  if (document.webkitExitFullscreen) return document.webkitExitFullscreen();
  // @ts-ignore
  if (document.mozCancelFullScreen) return document.mozCancelFullScreen();
  // @ts-ignore
  if (document.msExitFullscreen) return document.msExitFullscreen();
};

const toggleFullscreen = () => {
  if (isFullscreen()) {
    exitFullscreen();
  } else {
    requestFullscreen(document.documentElement);
  }
};
onMounted(async() => { 
 const acquire = await getClinicInfo();
  if (acquire && acquire.data) {
    formData.value = acquire.data; 
  }

  // 初次挂载刷新未读数
  getUnreadNumApi();
});
</script>

<style scoped lang="scss">
.header {
  width: 100%;
  height: 100%;
  background: var(--color-primary);
  box-shadow: var(--box-shadow-light);
  :deep(.el-badge__content){
    border: none;
  }
  :deep(.el-badge__content.is-fixed){
    top:5px;
  }
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    padding: 0 16px;
    margin: 0 auto;
  }

  .header-left {
    flex: 0 0 auto;

    .logo {
      display: flex;
      align-items: center;
      gap: 12px;

      .logo-img {
        width: 26px;
        height: 26px;
        border-radius: 6px;
      }

      .logo-text {
        font-weight: bold;
        font-size: 14px;
        color: #FFFFFF;
      }
    }
  }

  .header-center {
    flex: 1;
    display: flex;
    justify-content: center;
    padding: 0 40px;

    .nav-menu {
      display: flex;
      align-items: center;
      gap: 8px;

      .nav-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        color: rgba(255, 255, 255, 0.9);
        font-size: 13px;
        white-space: nowrap;

        .nav-icon {
          font-size: 18px;
        }

        .nav-text {
          font-size: 13px;
          font-weight: 500;
        }
        &.active {
          color: rgba(255, 255, 255, 0.9);
          font-size: 15px;
          position: relative;
          .nav-text {
            font-size: 15px;
            font-weight: 500;
          }
        }
        .active_line {
          width: 23px;
          height: 2px;
          background: #e8f7f7;
          border-radius: 0px 0px 0px 0px;
          position: absolute;
          top: 32px;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
  }

  .header-right {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 30px;
    justify-content: center;

    /* 去掉 el-dropdown 触发元素悬浮/聚焦时的黑色边框与阴影 */
    :deep(.el-dropdown .el-tooltip__trigger),
    :deep(.el-tooltip__trigger.el-dropdown-selfdefine) {
      outline: none !important;
      box-shadow: none !important;
    }
    :deep(.el-dropdown .el-tooltip__trigger:focus),
    :deep(.el-dropdown .el-tooltip__trigger:focus-visible),
    :deep(.el-tooltip__trigger.el-dropdown-selfdefine:focus),
    :deep(.el-tooltip__trigger.el-dropdown-selfdefine:focus-visible) {
      outline: none !important;
      box-shadow: none !important;
    }
    /* 触发容器本身的兜底处理 */
    .user-info:focus,
    .user-info:focus-visible {
      outline: none !important;
      box-shadow: none !important;
    }
    .user-info {
      display: flex;
      align-items: center;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      color: white;

      &:hover {
        background-color: rgba(255, 255, 255, 0.1);
      }

      .user-avatar {
        border: 2px solid rgba(255, 255, 255, 0.3);
      }

      .user-name {
        font-size: 15px;
        font-weight: 500;
        margin-left: 12px;
        white-space: nowrap;
        margin-right: 3px;
      }

      .dropdown-icon {
        font-size: 16px;
        transition: transform 0.3s ease;
      }

      &:hover .dropdown-icon {
        transform: rotate(180deg);
      }
    }

    .theme-wrapper {
      display: flex;
      align-items: center;
    }
  }
}
</style>
